import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class StatisticsGenerator {
	private static final long MAX_COST = 55969832;
	private static final long SUM_EXECUTIONS= 890407;
	TablesStatistics tablesStatistics = TablesStatistics.getStatistics();
	
	public StatisticsGenerator() {
		
	}
	
	public double calculateRatio(QueryStatistics statistics)
	{
		/*System.out.println(statistics.getElapsedTime());
		System.out.println(normalizeCost(statistics.getBufferGets() + statistics.getDiskReads()));
		System.out.println(normalizeExecutions(statistics.getExecutions()));
		System.out.println(calculateUpdateRatio(statistics.getSqlText(), statistics.getCommandType()));*/
		
		return (
					statistics.getElapsedTime()
						*
					normalizeCost(statistics.getBufferGets() + statistics.getDiskReads())
						*
					normalizeExecutions(statistics.getExecutions())
				)				
					/
				(
					calculateUpdateRatio(statistics.getSqlText(), statistics.getCommandType())
				);
	}
	
	private int calculateUpdateRatio(String query, CommandType cmdType)
	{
		ArrayList<Integer> stats = new ArrayList<Integer>();
		List<String> tableNames = FromClauseParser.parseFromClause(query, cmdType);
		for(String tableName : tableNames)
		{
			stats.add(tablesStatistics.getTotalModifications(tableName));
		}	 
		
		if(!stats.isEmpty() && Collections.max(stats).intValue()!=0)
		{
			return Collections.max(stats).intValue();			
		}
		
		return 1;
	}
	
	private double normalizeCost(double cost)
	{
		return cost / MAX_COST;
	}
	
	private double normalizeExecutions(double executions)
	{
		return executions ;/// SUM_EXECUTIONS;
	}
}
